package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.R;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;

import com.viewpagerindicator.TabPageIndicator;

public class BaseViewPagerFragment<T extends BaseListFragment> extends Fragment implements
		OnPageChangeListener, OnBaseListFragmentResumeListener {
	protected List<T> fragmentList = new ArrayList<T>();
	protected List<String> titleList = new ArrayList<String>();
	protected ViewPager pager;
	protected TabPageIndicator indicator;
	protected boolean hasBaseListFragmentResumed;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.base_fragment);
		pager = (ViewPager) view.findViewById(R.id.pager);
		indicator = (TabPageIndicator) view.findViewById(R.id.indicator);
		indicator.setOnPageChangeListener(this);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		ListFragmentPagerAdapter<T> adapter = new ListFragmentPagerAdapter<T>(
				getActivity().getSupportFragmentManager(), titleList,
				fragmentList);
		pager.setAdapter(adapter);
		indicator.setViewPager(pager);
	}

	private static class ListFragmentPagerAdapter<T extends BaseListFragment> extends
			FragmentStatePagerAdapter {
		private List<T> fragmentList;
		private List<String> titleList;

		public ListFragmentPagerAdapter(FragmentManager fm,
				List<String> titleList, List<T> fragmentList) {
			super(fm);
			this.titleList = titleList;
			this.fragmentList = fragmentList;
		}

		@Override
		public Fragment getItem(int position) {
			return fragmentList.get(position);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titleList.get(position);
		}

		@Override
		public int getCount() {
			return fragmentList.size();
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int arg0) {
		fragmentList.get(arg0).showList();
	}

	@Override
	public void onBaseListFragmentResume(BaseListFragment baseListFragment) {
		if(!isHasBaseListFragmentResumed()) {
			baseListFragment.showList();
			setHasBaseListFragmentResumed(true);
		} 
	}

	public boolean isHasBaseListFragmentResumed() {
		return hasBaseListFragmentResumed;
	}

	public void setHasBaseListFragmentResumed(boolean hasBaseListFragmentResumed) {
		this.hasBaseListFragmentResumed = hasBaseListFragmentResumed;
	}
}
